package com.anysoft.webloader;

import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * Http相关的工具类
 *
 * @version 1.6.14.6 [20210415 duanyy] <br>
 * - 增加获取baseUrl的方法; <br>
 */
public class HttpClientTool {
    /**
     * 支持ForwardedHeader
     */
    protected String ForwardedHeader = "X-Forwarded-For";
    protected String RealIp = "X-Real-IP";
    protected String RealUri = "X-Real-URI";
    protected String RealMethod = "X-Real-Method";

    public HttpClientTool(Properties p){
        ForwardedHeader = PropertiesConstants.getString(p,"http.forwardedheader", ForwardedHeader);
        RealIp = PropertiesConstants.getString(p,"http.realip", RealIp);
        RealUri = PropertiesConstants.getString(p,"http.realuri",RealUri);
        RealMethod = PropertiesConstants.getString(p,"http.realmethod",RealMethod);
    }

    public String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader(ForwardedHeader);
        if (StringUtils.isNotEmpty(ip)){
            String [] ips = ip.split(",");
            if (ips.length > 0){
                return ips[0];
            }else{
                return request.getRemoteHost();
            }
        }else{
            return request.getRemoteHost();
        }
    }

    public String getClientRealIp(HttpServletRequest request){
        String ip = request.getHeader(RealIp);
        return StringUtils.isNotEmpty(ip)?ip:request.getRemoteHost();
    }

    public String getRequestURI(HttpServletRequest request) {
        String uri = request.getHeader(RealUri);
        return StringUtils.isNotEmpty(uri)?uri:request.getRequestURI();
    }

    public String getOriginalRequestURI(HttpServletRequest request) {
        String uri = request.getHeader(RealUri);
        return StringUtils.isNotEmpty(uri)?uri:request.getRequestURI();
    }

    public String getHost(HttpServletRequest request) {
        return String.format("%s:%d",request.getLocalAddr(),request.getLocalPort());
    }

    public String getHostDomain(HttpServletRequest request){
        int port = request.getServerPort();
        if (((port == 80) && !request.isSecure()) || (port==443) && request.isSecure()){
            return request.getServerName();
        }else {
            return String.format("%s:%d", request.getServerName(), port);
        }
    }

    public String getPathInfo(HttpServletRequest request) {
        return request.getPathInfo();
    }

    public String getRequestURL(HttpServletRequest request) {
        String queryString = request.getQueryString();
        if (StringUtils.isNotEmpty(queryString)){
            return request.getRequestURL().toString() + "?" + queryString;
        }else{
            return request.getRequestURL().toString();
        }
    }

    public String getUrlBase(HttpServletRequest request){
        return String.format("%s://%s",request.getScheme(),getHostDomain(request));
    }

    public String getContextBase(HttpServletRequest request){
        return String.format("%s://%s%s",request.getScheme(),getHostDomain(request),request.getContextPath());
    }

    public String getMethod(HttpServletRequest request) {
        return request.getMethod();
    }

    public String getOriginalMethod(HttpServletRequest request){
        String uri = request.getHeader(RealMethod);
        return StringUtils.isNotEmpty(uri)?uri.toUpperCase():request.getMethod();
    }

    public String getRequestHeader(HttpServletRequest request,String name) {
        return request.getHeader(name);
    }

    public void setResponseHeader(HttpServletResponse response, String name, String value) {
        response.setHeader(name,escapeCRLF(value));
    }

    public void setResponseContentType(HttpServletResponse response,String contentType) {
        response.setContentType(escapeCRLF(contentType));
    }

    public void setResponseContentLength(HttpServletResponse response,int contentLength) {
        response.setContentLength(contentLength);
    }

    public String getQueryString(HttpServletRequest request) {
        return request.getQueryString();
    }

    public String getRequestContentType(HttpServletRequest request) {
        return request.getContentType();
    }

    public void setResponseEncoding(HttpServletResponse response,String encoding){
        response.setCharacterEncoding(escapeCRLF(encoding));
    }

    public void sendError(HttpServletResponse response,int code,String message) throws IOException {
        response.sendError(code,escapeCRLF(message));
    }

    public void sendRedirect(HttpServletResponse response,String location) throws IOException{
        response.sendRedirect(escapeCRLF(location));
    }

    public void setStatus(HttpServletResponse response,int code){
        response.setStatus(code);
    }

    private static String escapeCRLF(String value){
        return value.replaceAll("\r|\n", "");
    }
}
